Equality
Learn about equality in Go.
We'll cover the following
There are different ways to compare things in Go, none of them is perfect.
Operators == and !=#
The equality operator is the simplest and often most efficient way to
compare things in Go, but it only works on certain things. Most
notably it doesn’t work on slices or maps. Slices and maps can only
be compared to nil this way.
Using == you can compare basic types like int and string, and also
arrays and structs that have elements in them that can themselves
be compared using ==:
As soon as you add a property to the struct that can’t be compared
with ==, you need a whole other way to compare:
Writing specialized code#
If performance is important and you need to compare slightly more complicated types, your best bet might be comparing manually:
reflect.DeepEqual#
DeepEqual is the most generic way to compare things in Go, and it
can handle most of the things. Here is the catch:
DeepEqual is 100 times slower in this example than writing manual
code for comparing that struct.
Note that DeepEqual will compare unexported (lowercased) fields
from a struct as well. Also, two different types would never be
considered deeply equal even if they were two different structs with
identical fields and values.
Uncomparable things#
Some things can’t be compared and are considered unequal even to
themselves, such as floating-point variables with a NaN value or a
func type. If you have such fields in a struct for instance, the struct
won’t be DeepEqual to itself:
bytes.Equal#
bytes.Equal is a specialized way to compare byte slices. It’s much
faster than simply comparing two slices with a for loop.
Something worth being aware of, the bytes.Equal function considers
empty and nil slices to be equal, while reflect.DeepEqual does not.
Inheritance
Exercise: Comparing Structs